#include"TrPrRandom.h" 

#include"Song.h"

TrPrRandom::TrPrRandom(QList< QPointer<Song> > *songs, RepeatType repeat) : TrackProgression(songs), m_repeatType(repeat){
	m_index = -1;
	m_historyIndex = -1;
	for(int i = 0; i < songs->size(); i++){
		m_notPlayed.push_back((*songs)[i]);
	}
}

TrPrRandom::~TrPrRandom(){
	m_played.clear();
	m_notPlayed.clear();
}

bool TrPrRandom::next(){
	if(m_repeatType == RepeatOne && m_index > -1 && m_index < m_songs->size())
		return true;
	
	//History logic...
	if(m_historyIndex == 0)//End of history, continue normal random behaviour
		m_historyIndex--;
	else if(m_historyIndex > 0){//Still playing history, no random behaviour here.
		m_historyIndex--;
		m_index = m_songs->indexOf(m_played[m_historyIndex]);
		return true;
	}
	
	Song *avoidPicking = 0;
	
	//The repeat logic...
	if(m_notPlayed.size() == 0){
		if(m_repeatType == NoRepeat){
			m_index = -1;
			m_notPlayed = m_played;
			return false;
		}
		//Making sure last played song won't be repeated immediately. 
		//This would result in a list of 2 songs being played sequentially, but meh.
		if(m_played.size() > 1)
			avoidPicking = m_played[0];
		m_notPlayed = m_played;
		m_played.clear();
	}
	
	//The random logic...
	bool done = false;
	//I once witnessed the player get stuck in this function ... Since this is the only while loop used, better playing safe.
	for(short unsigned int i = 0; i < 20 && !done; i++){
		int n = (qrand() % m_notPlayed.size());
		if(m_notPlayed[n] == avoidPicking)
			continue;
		m_played.push_front(m_notPlayed.takeAt(n));
		m_index = m_songs->indexOf(m_played[0]);
		done = true;
	}
	
	return true;
}

void TrPrRandom::previous(){
	if(m_played.size()==0){
		m_index = -1;
		return;
	}
	
	if(m_historyIndex== -1)//To avoid replaying current song.
		m_historyIndex = 0;

	if(m_historyIndex >= m_played.size())//This can't happen...
		m_historyIndex = m_played.size() - 2;//Will be incremented till last song below.
	
	if(m_historyIndex == m_played.size()-1)
		return;//Will cause current song to be re-played.
	
	m_historyIndex++;
	m_index = m_songs->indexOf( m_played[m_historyIndex] );
	return;
}

int TrPrRandom::current(){
	return m_index;
}

void TrPrRandom::setIndex(short int index){
	Song *song = (*m_songs)[index];
	if(m_played.contains(song))//TODO Should be tested if this works with QPointer logic...
		m_played.push_front( m_played.takeAt(m_played.indexOf(song)) );
	else
		m_played.push_front( m_notPlayed.takeAt(m_notPlayed.indexOf(song)) );
	m_index = index;
}

void TrPrRandom::songAdded(QPointer<Song> song){
	m_notPlayed.push_back(song);
}

void TrPrRandom::songRemoved(QPointer<Song> song){
	if(m_played.contains(song))
		m_played.removeAll(song);
	if(m_notPlayed.contains(song))
		m_notPlayed.removeAll(song);
}

void TrPrRandom::cleared(){
	m_played.clear();
	m_notPlayed.clear();
	m_historyIndex = -1;
	m_index = -1;
}

